package com.mvcplus.system.service.impl;

import com.baomidou.framework.service.impl.SuperServiceImpl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mvcplus.common.model.SessionInfo;
import com.mvcplus.common.utils.MD5Util;
import com.mvcplus.system.mapper.SysResourceMapper;
import com.mvcplus.system.mapper.SysRoleResourceMapper;
import com.mvcplus.system.mapper.SysUserMapper;
import com.mvcplus.system.mapper.SysUserRoleMapper;
import com.mvcplus.system.model.SysResource;
import com.mvcplus.system.model.SysUser;
import com.mvcplus.system.model.SysUserRole;
import com.mvcplus.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * SysUser 表数据服务层接口实现类
 *
 */
@Service
public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private  SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysRoleResourceMapper sysRoleResourceMapper;

    @Autowired
    private SysResourceMapper sysResourceMapper;


    @Override
    public List<String> getResourceList(Long userid) {

        //定义结果集
        List<String> urlList=new ArrayList();

        //先查出该用户角色
        EntityWrapper ew = new EntityWrapper();
        ew.where("U_ID={0}", userid);
        List<SysUserRole> surList = sysUserRoleMapper.selectList(ew);
        //角色Ids
        List<Long> roleIds= new ArrayList();
        for (SysUserRole sur:surList){
            roleIds.add(sur.getRoleId());
        }

        //根据角色查资源权限
        List<SysResource> resList = sysResourceMapper.selectResourceByRole(roleIds);
        for (SysResource res:resList){
            urlList.add(res.getUrl());
        }

        return urlList;
    }

    @Override
    public List<String> getAllResourceList() {
        List<String> urlList=new ArrayList();
        List<SysResource> resList = sysResourceMapper.selectList(null);
        for (SysResource res:resList){
            urlList.add(res.getUrl());
        }
        return urlList;
    }

    @Override
    public Boolean editUserPwd(SessionInfo sessionInfo, String oldPwd, String newPwd) {
        SysUser u = sysUserMapper.selectById(sessionInfo.getId());
        if (u.getPassword().equalsIgnoreCase(MD5Util.md5(oldPwd))) {// 说明原密码输入正确
            u.setPassword(MD5Util.md5(newPwd));
            sysUserMapper.updateSelectiveById(u);
            return true;
        }
        return false;
    }
}